import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
import index from '@/views/index'
import login from '@/views/login'
// 按需加载
const indexbody = () => import(/* webpackChunkName: "index" */ '@/views/index_body.vue')
const channel = () => import(/* webpackChunkName: "channel" */ '@/views/channel/channel.vue')
const articleedit = () => import(/* webpackChunkName: "channel" */ '@/views/article/article_edit.vue')
const articleadd = () => import(/* webpackChunkName: "channel" */ '@/views/article/article_add.vue')
Vue.use(Router)
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: index,
      // meta: { requireLogin: true }
      meta: {
        breadcrumb: '首页'
      },
      children: [
        {
          path: '/index',
          name: 'index_body',
          component: indexbody
        },
        {
          path: '/channel/:id',
          name: 'channel',
          component: channel
        },
        {
          path: '/article/edit/:id',
          name: 'articleedit',
          component: articleedit
        },
        {
          path: '/article/add/:id',
          name: 'articleadd',
          component: articleadd
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: { requireLogin: true }
    }
  ]
})
if (localStorage.getItem('token')) {
  store.commit('BIND_LOGIN', localStorage.getItem('token'))
}
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireLogin)) { // 判断该路由是否需要登录权限
    next()
  } else {
    if (store.getters.token) { // 判断当前用户的登录信息loginInfo是否存在
      next()
    } else {
      next({ path: '/login' })
    }
  }
})

export default router
